<template>
    <li>
      <div>
        <span v-if="node.children" @click="toggleExpand">
          {{ node.expanded ? '[-]' : '[+]' }}
        </span>
        <el-checkbox 
          v-model="node.checked" 
          :indeterminate="node.indeterminate"
          @change="handleCheckChange"
        >
          <!-- <template #label> -->
            <span style="color: white;">{{ node.label }}</span>
          <!-- </template> -->
        </el-checkbox>
      </div>
      <ul v-if="node.children && node.expanded">
        <tree-node 
          v-for="child in node.children" 
          :key="child.id" 
          :node="child" 
          @toggle="$emit('toggle', child)" 
          @check="handleCheck"
        />
      </ul>
    </li>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue';
import { ElCheckbox } from 'element-plus';

interface TreeNode {
  id: number;
  label: string;
  children?: TreeNode[];
  checked?: boolean;
  expanded?: boolean;
  indeterminate?: boolean;
}

export default defineComponent({
  name: 'TreeNode',
  components: { ElCheckbox },
  props: {
    node: {
      type: Object as PropType<TreeNode>,
      required: true,
    },
  },
  emits: ['toggle', 'check'],
  methods: {
    toggleExpand() {
      this.$emit('toggle', this.node);
    },
    handleCheckChange() {
      this.updateChildCheckState(this.node, this.node.checked);
      this.$emit('check', this.node);
    },
    handleCheck(node: TreeNode) {
      this.updateParentState(this.node);
      this.$emit('check', node);
    },
    updateChildCheckState(node: TreeNode, checked: boolean) {
      if (node.children) {
        node.children.forEach(child => {
          child.checked = checked;
          child.indeterminate = false;
          this.updateChildCheckState(child, checked);
        });
      }
    },
    updateParentState(node: TreeNode) {
      if (node.children) {
        const allChecked = node.children.every(child => child.checked);
        const someChecked = node.children.some(child => child.checked || child.indeterminate);

        node.checked = allChecked;
        node.indeterminate = !allChecked && someChecked;
      }
    },
  },
});
</script>

<!-- scoped 作用域确保样式只应用于 TreeNode.vue 组件内的元素 -->
<style scoped>

/* 展开收起样式效果 */
li {
  list-style-type: none;
  color: white;
}

</style>
